package com.huika.renrench.control.common.base;

import java.io.UnsupportedEncodingException;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.android.volley.Request;
import com.android.volley.Response.ErrorListener;
import com.android.volley.VolleyError;
import com.hk.app.android.lib.http.VolleyRequestManager;
import com.huika.lib.base.R;
import com.huika.lib.ui.framelayout.activity.BaseActivity;
import com.huika.lib.ui.widget.LoadingDialog;
import com.huika.lib.ui.widget.ToastMsg;
import com.huika.lib.ui.widget.overlay.OverlayLayout;
import com.huika.lib.utils.VerifyTool;
import com.huika.renrench.http.ServerFlagError;
import com.huika.renrench.http.ServerJsonUnParseError;

public abstract class BaseAct extends BaseActivity implements ErrorListener,
		OnCancelListener{
	public static final String LEFT_TITLE = "leftTitle";// 所有左侧显示字符的传递key
	/** 分页加载数据，每页数据量 */
	public static final int PAGE_SIZE = 10;
	/** 当前页，用于分页加载数据 */
	public int CURRENT_PAGE = 1;
	protected LayoutInflater inflater;
	protected Context context;
	public LoadingDialog loadingDialog;
	protected View netErrorView;
	
	public BaseAct() {
		setHiddenActionBar(true);
		// setBackListener(false);
		// setScreenOrientation(ScreenOrientation.VERTICAL);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		context = this;
		inflater = LayoutInflater.from(context);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		super.onCreate(savedInstanceState);
	}

	protected void initLoadingDialog(boolean isTrans){
		if (null == loadingDialog) {
			loadingDialog = new LoadingDialog(this, isTrans);
			loadingDialog.setOnCancelListener(this);
		}
	}
	
	public void showLoadingDialog(String parameter) {
		initLoadingDialog(true);//透明
		loadingDialog.setTitle(parameter);
		if(!loadingDialog.isShowing())
			loadingDialog.show();
	}

	public void dismissLoadingDialog() {
		if (null != loadingDialog) {
			LoadingDialog.dismissDialog(loadingDialog);
		}
	}

	public void showToastMsg(String msg) {
		ToastMsg.showToastMsg(this, msg);
	}

	public void showToastMsg(int strId) {
		ToastMsg.showToastMsg(this, strId);
	}

	// 旧的网络错误显示
	// /***
	// * 事件监听view的id=R.id.click_reload
	// * 显示加载异常
	// *
	// * @param reloadListener
	// */
	// public void showNetError(View.OnClickListener reloadListener) {
	// if (netErrorView == null) {
	// ViewGroup contentView = ((ViewGroup) findViewById(android.R.id.content));
	// netErrorView = inflater.inflate(R.layout.common_load_error, contentView,
	// false);
	// contentView.addView(netErrorView);
	// }
	// if (reloadListener != null) {
	// netErrorView.findViewById(R.id.click_reload).setOnClickListener(reloadListener);
	// }
	// netErrorView.setVisibility(View.VISIBLE);
	// }
	//
	// /**
	// * 隐藏加载异常
	// */
	// public void hideNetError() {
	// if (netErrorView != null) {
	// netErrorView.setVisibility(View.GONE);
	// }
	// }

	/***
	 * 事件监听view的id=R.id.click_reload 显示加载异常
	 * 
	 * @param reloadListener
	 */
	protected void setNetErrorClick(View.OnClickListener reloadListener) {
		initNetErrorView();
		if (reloadListener != null){
			netErrorView.findViewById(R.id.click_reload).setOnClickListener(reloadListener);
			netErrorView.findViewById(R.id.click_checknetwork).setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// 检查网络设置
					Intent intent= new Intent(Settings.ACTION_SETTINGS);
	                startActivity(intent);
				}
			});
		}
	}

	protected View initNetErrorView() {
		if (netErrorView == null) {
			initOverlayLayout();
			netErrorView = mOverlayLayout
					.setOverlayView(R.layout.common_load_error);
		}
		return netErrorView;
	}

	protected void initOverlayLayout() {
		if (mOverlayLayout == null)
			mOverlayLayout = new OverlayLayout(this);
	}

	/** 设置overlay依附的viewgroup */
	protected void setOverLayAttachTo(View targetView) {
		initOverlayLayout();
		mOverlayLayout.attachTo(targetView);
	}

	private Set<Object> tags = new HashSet<Object>();

	/**
	 * 添加网络请求
	 * 
	 * @param request
	 */
	protected void executeRequest(Request request) {
		VolleyRequestManager.addRequest(request, this);
		tags.add(this);
	}

	/**
	 * 添加网络请求
	 * 
	 * @param request
	 */
	protected void executeRequest(Request request, Object tag) {
		VolleyRequestManager.addRequest(request, tag);
		tags.add(tag);
	}

	/**
	 * 取消网络请求
	 * 
	 * @param tag
	 */
	protected void cancelRequest(Object tag) {
		VolleyRequestManager.cancelAll(tag);
	}

	@Override
	public void onStop() {
		super.onStop();
		for (Object tag : tags) {
			VolleyRequestManager.cancelAll(tag);
		}
	}
	
	/** 校验输入 *************************/
	/* 获取输入内容 */
	public String getInputStr(EditText et) {
		return et.getText().toString().trim();
	}

	/**
	 * 校验密码格式
	 */
	protected boolean checkPWD(String inputStr, boolean checkEmpty) {
		if (checkEmpty && TextUtils.isEmpty(inputStr)) {
			showToastMsg(R.string.register_code_empty_pwd);
			return false;
		} else if (!VerifyTool.isCheckLength(inputStr, 8, 16)) {
			showToastMsg("请输入8-16位密码");
			return false;
		}
		return true;
	}

	/**
	 * 找回密码判断
	 * 
	 * @description：
	 * @author ldm
	 * @date 2014年12月25日 下午7:03:47
	 */
	protected boolean findPWD(String inputStr, boolean checkEmpty) {
		if (checkEmpty && TextUtils.isEmpty(inputStr)) {
			showToastMsg(R.string.register_code_empty_pwd_tips);
			return false;
		} 
		
		if(inputStr.contains(" ")){
			showToastMsg("密码中不能有空格");
			return false;
		}
		
		else if (!VerifyTool.isCheckLength(inputStr, 8, 16)) {
			showToastMsg("请输入8-16位密码");
			return false;
		}
		return true;
	}

	protected boolean checkPWDLogin(String inputStr, boolean checkEmpty) {
		if (checkEmpty && TextUtils.isEmpty(inputStr)) {
			showToastMsg(R.string.register_code_empty_pwd_tips);
			return false;
		}
//		else if (!VerifyTool.isCheckLength(inputStr, 8, 16)) {
//			showToastMsg("密码错误");
//			return false;
//		}
		return true;
	}

	/**
	 * 校验邮箱
	 */
	protected boolean checkEmial(String inputStr, boolean checkEmpty) {
		if (checkEmpty && TextUtils.isEmpty(inputStr)) {
			showToastMsg(R.string.register_code_empty_email);
			return false;
		} else if (!VerifyTool.isEmail(inputStr)) {
			showToastMsg("邮箱格式不正确，请重新输入！");
			return false;
		}
		return true;
	}

	/**
	 * @description：校验帐号输入
	 */
	protected boolean checkAccountInput(String inputStr, boolean checkEmpty) {
		if (TextUtils.isEmpty(inputStr) && checkEmpty) {
			showToastMsg(R.string.register_code_empty_account);
			return false;
		}
		if (!VerifyTool.isCheckLength(inputStr, 4, 32)) {
			showToastMsg("账号由4到32位字符构成");
			return false;
		}
		return true;
	}

	/**
	 * 校验短信验证码
	 * 
	 * @param checkEmpty
	 */
	protected boolean checkMsg(String inputStr, boolean checkEmpty) {
		if (checkEmpty && TextUtils.isEmpty(inputStr)) {
			showToastMsg(R.string.register_code_empty_verify_code);
			return false;
		}

		// if (!VerifyTool.isSmsCode(inputStr)) {
		// showToastMsg("验证码输入错误");
		// return false;
		// }
		return true;
	}

	/**
	 * 校验手机号
	 */
	protected boolean checkPhone(String inputStr, boolean checkEmpty) {
		if (checkEmpty && TextUtils.isEmpty(inputStr)) {
			showToastMsg(R.string.register_code_empty_phone_number);
			return false;
		} else if (!VerifyTool.isMobileNO(inputStr)) {
			showToastMsg("请输入正确的手机号码");
			return false;
		}
		return true;
	}

	/**
	 * @description：校验是都为银行卡号
	 * @author shicm
	 * @date 2014年8月19日 下午6:31:59
	 */
	protected boolean isBankCard(String str) {
		if (TextUtils.isEmpty(str)) {
			return false;
		}

		String scard = str.trim();
		Pattern pattern = Pattern.compile("^\\d{15,1000}$");
		return pattern.matcher(scard).matches();
	}

	/**
	 * 校验身份证
	 */
	protected boolean checkIdno(String inputStr, boolean checkEmpty) {
		// TODO
		if (checkEmpty && TextUtils.isEmpty(inputStr)) {
			showToastMsg("请输入身份证号！");
			return false;
		}
		if (!(VerifyTool.verifyPasswordFormat(inputStr)
				&& inputStr.length() <= 18 && inputStr.length() >= 6)) {
			showToastMsg("身份证号码格式不对！");
			return false;
		}
		return true;
	}

	// 默认网络请求异常回调
	@Override
	public void onErrorResponse(VolleyError error) {
		dismissLoadingDialog();
		if (CURRENT_PAGE > 1) {// 加载异常回退到当前页
			CURRENT_PAGE--;
		}
		String msg = "网络异常";
		if (error instanceof ServerFlagError) {
			msg = ((ServerFlagError) error).result.msg;
		} else if (error instanceof ServerJsonUnParseError) {
			try {
				String res = ((ServerJsonUnParseError) error).result;
				JSONObject jsonObject = new JSONObject(res);
				msg = jsonObject.getString("msg");
			} catch (JSONException e) {
				e.printStackTrace();
			}
		} else {
			try {
				if (error.networkResponse != null
						&& error.networkResponse.data != null){
					msg = new String(error.networkResponse.data, "utf-8");
					if(TextUtils.isEmpty(msg)){
						msg = "未知异常";
					}
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		showToastMsg(msg);
	}

	@Override
	public void startActivity(Intent intent) {
		super.startActivity(intent);
		overridePendingTransition(R.anim.activity_right_in,
				R.anim.activity_right_out);
	}

	@Override
	public void startActivityForResult(Intent intent, int requestCode) {
		super.startActivityForResult(intent, requestCode);
		overridePendingTransition(R.anim.activity_right_in,
				R.anim.activity_right_out);
	}

	/**
	 * loadingdialog取消监听
	 */
	@Override
	public void onCancel(DialogInterface dialog) {
	}

	/** 覆盖页 ******************************/
	protected OverlayLayout mOverlayLayout;

	protected void showOverLay() {
		if (mOverlayLayout != null) {
			mOverlayLayout.showOverlay();
		}
	}

	protected void hideOverLay() {
		if (mOverlayLayout != null) {
			mOverlayLayout.hideOverlay();
		}
	}

	/** 覆盖页 end ******************************/

	/**
	 * @Description: TODO:：关闭键盘事件
	 * @author: 刘成伟（wwwlllll@126.com）
	 * @Title: closeInput
	 * @param
	 * @return void
	 * @throws
	 * @date 2014-4-6 上午11:18:36
	 */
	public void closeInput() {
		InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		if (inputMethodManager != null && this.getCurrentFocus() != null) {
			inputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus()
					.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}
}
